#!/bin/bash
set -e
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "./NINJA-0.97.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then echo "请输入正确的构建路径"; exit 1; fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then echo "请输入正确的安装路径"; exit 1; fi
[[ "$1" = "$2" ]] && echo "构建路径与安装路径不能相同" && exit 1
buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi

wget -t 10 -c -P $installpath https://github.com/TravisWheelerLab/NINJA/archive/0.97-cluster_only.tar.gz -O $installpath/NINJA-cluster.tar.gz
cd $installpath
mkdir -p NINJA
tar -xf NINJA-cluster.tar.gz -C NINJA  --strip-components 1
cd NINJA/NINJA
sed -i -e 's/g++/clang++/g' \
	-e 's/-mssse3/-march=armv8-a+fp+simd+crc -fsigned-char/g' Makefile

#use sse2neon to adapt arm
wget -t 10 -c https://github.com/DLTcollab/sse2neon/archive/refs/tags/v1.5.1.tar.gz
tar xf v1.5.1.tar.gz
mv sse2neon-1.5.1 sse2neon
sed -i '15,17c #include "sse2neon/sse2neon.h"' DistanceCalculator.hpp
make clean && make -j$(nproc) all CXX=clang++
rm -rf $installpath/NINJA-cluster.tar.gz
cat>"$installpath/NINJA/NINJA_modulefiles"<<EOF
#%Module1.0
conflict NINJA
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set NINJA \$pwd
setenv NINJA \$NINJA
prepend-path PATH \$NINJA/NINJA
EOF
